﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel.Composition;

namespace Kindler.Processors
{
    [Export(typeof(IProcessor))]
    public class TableOfContentsProcessor : IProcessor
    {
        public void Process(XDocument htmlBook)
        {
            XElement body = htmlBook.Descendants("body").SingleOrDefault();

            var chapterHeaders = from header in htmlBook.Descendants("h1")
                                 select header;

            var tocList = new XElement("ul");

            int headerCount = 0;

            foreach (var header in chapterHeaders)
            {
                var link = new XElement("a", header.Value);
                link.Add(new XAttribute("href", "#h" + headerCount));

                tocList.Add(new XElement("li", link));
                header.AddFirst(new XElement("a", new XAttribute("name", "h" + headerCount)));

                headerCount++;
            }

            var container = new XElement("div", new XAttribute("id", "toc"),
                new XElement("h1", "Table of Contents"), new XElement("br"));

            container.Add(tocList);
            container.AddFirst(new XElement("a", new XAttribute("name", "TOC")));

            body.AddFirst(container);
        }
    }
}